package cn.laixueit.controller;

import cn.laixueit.common.RedisFInal;
import cn.laixueit.common.Utils;
import cn.laixueit.pojo.User;
import cn.laixueit.result.Result;
import cn.laixueit.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import redis.clients.jedis.Jedis;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private Jedis jedis;

    @PostMapping("/login")
    public Result login(@RequestBody User user, HttpSession session){
        User u = userService.login(user);
        u.setPassword("");
        session.setAttribute("u",u);
        return new Result();
    }
    @GetMapping("/logout")
    @ResponseBody
    public Result logout(HttpSession session){
        session.removeAttribute("u");
        return new Result();
    }




    @GetMapping("/verify")
    public String verify(HttpSession session){
        User u = (User) session.getAttribute("u");
        if(u!=null){
            return u.getUsername();
        }
        return null;
    }

    @GetMapping("/getCode")
    @ResponseBody
    public Result getCode(String email){
        Integer code = Utils.sendMail(email);
        jedis.select(RedisFInal.INDEX);
        jedis.set(email+":code",code.toString());
        jedis.expire(email+":code",300);
        return  new Result();
    }

    @PostMapping("/register")
    public Result regirest(@RequestBody User user){
        userService.regirest(user);
        return  new Result();
    }
}
